package com.ideaplugin.datamanager.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;
import java.util.function.Supplier;

public class DynamicDataSource extends AbstractRoutingDataSource {

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return getDataSource();
    }

    public static void setDataSource(String dataSourceName) {
        contextHolder.set(dataSourceName);
    }

    public static <T> T setDataSourceAndExecute(String dataSourceEnum, Supplier<T> supplier) {
        try {
            DynamicDataSource.setDataSource(dataSourceEnum);
            return supplier.get();
        } finally {
            DynamicDataSource.clearDataSource();
        }
    }


    public static String getDataSource() {
        return contextHolder.get();
    }

    public static void clearDataSource() {
        contextHolder.remove();
    }


}
